package com.hadoop.project.gen.maodalitest;

import com.hadoop.project.entity.constant.PreProcessingDataModifier;
import com.hadoop.project.entity.hbase.*;
import com.hadoop.project.entity.po.TabRank;
import com.hadoop.project.entity.po.UserFlavor;
import com.hadoop.project.entity.po.VideoRank;
import com.hadoop.project.gen.maodaligendata.GenConstant;
import com.hadoop.project.entity.hbase.ProcessRes;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Alexmaodali
 * @usage:这是我计算的地方
 */
public class TestProcessingData extends PreProcessingDataModifier {

    public static HBaseResult genHBaseData(  Integer genVideoLen,  Integer genUserLen,  Integer genUserLogLen) throws Exception {

        List<Tab> tabList               = new ArrayList<>();
        List<String> tidList            = new ArrayList<>();
        List<String> uidList            = new ArrayList<>();
        List<String> vidList            = new ArrayList<>();
        List<Video> videoList           = new ArrayList<>();
        List<UserLog> userLogList       = new ArrayList<>();
        List<HBaseUser> hBaseUserList   = new ArrayList<>();
        Map<String, String> vidMapFlip  = new HashMap<>();

        for (int i = 0; i < GenConstant.tabList.length; i++) {
            String uniqueTid = "tid-" + (i + 1);
            if (tidList.contains(uniqueTid)) {
                continue;
            }
            Tab tab = Tab.builder().tid(uniqueTid).tname(GenConstant.tabList[i]).build();
            tidList.add(tab.getTid());
            tabList.add(tab);
        }
        // 生成User数据
        for (int i = 0; i < genUserLen; i++) {
            HBaseUser user = HBaseUser.builder().uid(GenConstant.genUid(10)).nickName(GenConstant.genNickName()).sex(GenConstant.genSex()).age(GenConstant.genAge()).province(GenConstant.genProvince()).build();
            uidList.add(user.getUid());
            hBaseUserList.add(user);
        }
        // 生成Video数据
        for (int i = 0; i < genVideoLen; i++) {
            Video video = Video.builder().vid(GenConstant.genLongTypeVID(10)).tabs(GenConstant.genTabs(tidList)).author(GenConstant.genAuthor(uidList)).flip(GenConstant.genFlip()).build();
            vidList.add(video.getVid());
            vidMapFlip.put(video.getVid(), video.getFlip());
            videoList.add(video);
        }
        // 生成UserLog数据
        for (int i = 0; i < genUserLogLen; i++) {
            UserLog userLog = UserLog.builder().uid(GenConstant.genAuthor(uidList)).id("userLog-" + (i + 1)).vid(GenConstant.genVidInUserLog(vidList)).videoTime(GenConstant.genVideoTime(10)).build();
            String flip = vidMapFlip.get(userLog.getVid());
            userLog.setVideoTime(flip);
            userLogList.add(userLog);
        }
        return HBaseResult.builder().tabList(tabList).videoList(videoList).hBaseUserList(hBaseUserList).userLogList(userLogList).build();
    }

    /**
     * 处理hbase数据
     * @param hBaseResult
     * @return
     */
    public static ProcessRes processHBaseData(HBaseResult hBaseResult) {
        // 预处理hbase数据
        if (needResolve) {
            hBaseResult = preProcessingData(hBaseResult);
        }

        // 处理VideoRank
        Map<String, Long> videoCountMap = new HashMap<>();
        for (UserLog userLog : hBaseResult.getUserLogList()) {
            String vid = userLog.getVid();
            videoCountMap.put(vid, videoCountMap.getOrDefault(vid, 0L) + 1);
        }
        List<VideoRank> videoRankList = videoCountMap.entrySet().stream().sorted(Map.Entry.<String, Long>comparingByValue().reversed()).map(entry -> VideoRank.builder().videoId(entry.getKey()).views(entry.getValue()).build()).collect(Collectors.toList());
        long videoId = 1;
        for (VideoRank vr : videoRankList) {
            vr.setId(videoId++);
        }

        // 处理TabRank
        Map<String, String> tidToTname = hBaseResult.getTabList().stream().collect(Collectors.toMap(Tab::getTid, Tab::getTname));
        Map<String, Long> tnameCountMap = new HashMap<>();
        for (Video video : hBaseResult.getVideoList()) {
            String[] tids = video.getTabs().split(",");
            for (String tid : tids) {
                String tname = tidToTname.get(tid);
                if (tname != null) {
                    tnameCountMap.put(tname, tnameCountMap.getOrDefault(tname, 0L) + 1);
                }
            }
        }

        List<TabRank> tabRankList = hBaseResult.getTabList().stream().map(tab -> {
            String tname = tab.getTname();
            Long cnt = tnameCountMap.getOrDefault(tname, 0L);
            return TabRank.builder().tname(tname).cnt(cnt).build();
        }).collect(Collectors.toList());
        tabRankList.sort(Comparator.comparingLong(TabRank::getCnt).reversed());
        long tabId = 1;
        for (TabRank tr : tabRankList) {
            tr.setId(tabId++);
        }

        // 处理UserFlavor
        // 1. 重新计算正确的标签总次数（所有用户观看次数总和）
        Map<String, Long> totalTagCountMap = new HashMap<>();
        for (UserLog userLog : hBaseResult.getUserLogList()) {
            String vid = userLog.getVid();
            Video video = hBaseResult.getVideoList().stream().filter(v -> v.getVid().equals(vid)).findFirst().orElse(null);
            if (video == null) continue;
            String[] tids = video.getTabs().split(",");
            for (String tid : tids) {
                String tname = tidToTname.get(tid);
                if (tname != null) {
                    totalTagCountMap.put(tname, totalTagCountMap.getOrDefault(tname, 0L) + 1);
                }
            }
        }

        // 2. 统计用户标签观看次数
        Map<String, Map<String, Long>> userTagCountMap = new HashMap<>();
        for (UserLog userLog : hBaseResult.getUserLogList()) {
            String uid = userLog.getUid();
            String vid = userLog.getVid();
            Video video = hBaseResult.getVideoList().stream().filter(v -> v.getVid().equals(vid)).findFirst().orElse(null);
            if (video == null) continue;
            String[] tids = video.getTabs().split(",");
            for (String tid : tids) {
                String tname = tidToTname.get(tid);
                if (tname == null) continue;
                userTagCountMap.computeIfAbsent(uid, k -> new HashMap<>()).merge(tname, 1L, Long::sum);
            }
        }

        List<UserFlavor> userFlavorList = new ArrayList<>();
        for (HBaseUser user : hBaseResult.getHBaseUserList()) {
            String uid = user.getUid();
            Map<String, Long> userTags = userTagCountMap.getOrDefault(uid, new HashMap<>());
            for (String tname : totalTagCountMap.keySet()) {
                Long userCount = userTags.getOrDefault(tname, 0L);
                Long totalCount = totalTagCountMap.getOrDefault(tname, 0L);
                // 修正百分比计算逻辑
                double percent = totalCount == 0 ? 0.0 : (userCount * 100.0) / totalCount;
                String tpercent = String.format("%.1f%%", percent);

                userFlavorList.add(UserFlavor.builder().uid(Long.parseLong(uid)).tname(tname).tpercent(tpercent).build());
            }
        }

        long userFlavorId = 0;
        for (UserFlavor uf : userFlavorList) {
            uf.setId(userFlavorId++);
        }
        userFlavorList.sort((a, b) -> {
            double aVal = Double.parseDouble(a.getTpercent().replace("%", ""));
            double bVal = Double.parseDouble(b.getTpercent().replace("%", ""));
            return Double.compare(bVal, aVal);
        });

        return ProcessRes.builder().tabRankList(tabRankList).videoRankList(videoRankList).userFlavorList(userFlavorList).build();
    }

}
